package com.boxfishedu.foreignkey.entity.jpa;

import com.boxfishedu.foreignkey.entity.Student;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * Created by lzx on 16/3/9.
 */
public class StudentJpaRepositoryImpl implements StudentJpaRepositoryCustom {

    @PersistenceContext
    EntityManager entityManager;

    @Override
    public List<Student> findByGrade(String grade) {

        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

        CriteriaQuery<Student> teacherCriteriaQuery = criteriaBuilder.createQuery(Student.class);
        Root<Student>studentRoot = teacherCriteriaQuery.from(Student.class);
        Predicate predicate = criteriaBuilder.equal(studentRoot.get("grade"),grade);
        return entityManager.createQuery(teacherCriteriaQuery.where(predicate)).getResultList();

    }
}
